﻿/*********************************************************************/
/**公共函数，需要Jquery、Bootstrap支持 以及 引入国际化语言配置message*.js
/*********************************************************************/

var web_site_domain = "http://localhost:8080/";
var web_app_root = "Idea/";
var noimage = "images/no_photo.jpg";

/**
 * 页面初始化事件注册
 */
$(function(){
	
	if($('.modal[id$=Modal]').length>0){
		$('.modal[id$=Modal]').modal({backdrop: 'static', keyboard: false, show: false});
	}
	//初始化日期插件语言包
	if ($.fn.datepicker){
		$.fn.datepicker.dates['en'] = _lang.datepicker.dates;
		$.fn.datepicker.dates['zh'] = _lang.datepicker.dates;
    }
	if($.fn.datetimepicker){
		$.fn.datetimepicker.dates['en'] = _lang.datepicker.dates;
		$.fn.datetimepicker.dates['zh'] = _lang.datepicker.dates;
	}
	
	//返回按钮事件
	$('.goBackBtn').click(function(){
		var referer = $('input[name="referer"]');
		if(referer.length>0&&referer.val()!='')	window.location.href = referer.val();
		else history.back(-1);
    });
	
	//全选
    $('.checkAll').click(function(){
        if($(this).is(':checked') || !$(this).hasClass('HasChecked')){
        	$(this).addClass('HasChecked');
            $('input[type="checkbox"][name="checkAll"]:not(:disabled)').prop('checked',true).parent('span').addClass('checked');
        }else{
        	$(this).removeClass('HasChecked');
            $('input[type="checkbox"][name="checkAll"]:not(:disabled)').prop('checked',false).parent('span').removeClass('checked');
        }
    });
    $('table th input:checkbox').on('click', function () {
        var that = this;
        $(this).closest('table').find('tr > td:first-child input:checkbox')
        .each(function () {
            this.checked = that.checked;
            $(this).closest('tr').toggleClass('selected');
        });

    });
    
	//工具提示
    if($('[tooltip-title]').length>0){
    	$('[tooltip-title]').tooltip({title:function(){return $(this).attr('tooltip-title')},placement:'top'});
    }
    
    //后台导航菜单展开
    if($('[nav-menu]').length>0){
    	$('ul.page-sidebar-menu>li').removeClass('start').removeClass('open').removeClass('active')
    		.find('li,.arrow').removeClass('active').removeClass('open');
    	$('.'+$('[nav-menu]:last').attr('nav-menu')).addClass('active')
    		.parent('ul.sub-menu').parent('li').addClass('active').addClass('open')
    		.children('a:first').find('.arrow').addClass('open');
    }
    
    //前台导航选择样式
    if($('[home-nav]').length>0){
    	$('.navbar ul.nav>li').removeClass('active');
    	$('.navbar ul.nav>li.'+$('[home-nav]').attr('home-nav')).addClass('active');
    }
    
	//关键字高亮
    highlight('input[name="keyword"]:not(.nofocus)','.hlight');
    $('input[name="keyword"]:not(.nofocus)').bind('keyup change', function(ev) {
    	highlight(this,'.hlight');
    }).focus();
    if($('input[for-hlight]').length>0){
	    $('input[for-hlight]').each(function(){
	    	$($(this).attr('for-hlight')).removeHighlight().highlight($(this).val())
	    });
	    $('input[for-hlight]').bind('keyup change', function(ev) {
	    	$($(this).attr('for-hlight')).removeHighlight().highlight($(this).val())
	    });
    }
    
    //保持心跳
    setInterval(function(){
    	$.post("./responseAjax?data="+new Date().getTime(),function(resp){
    		console.log(resp);
    	})
    }, 60000);

	//离开页面前执行
    if(typeof getFormData=='function'){
    	loadingModal(_lang.loadingmsg);
    	setTimeout(function(){
    		loadingModal();
    		refreshFormData();
        	window.onbeforeunload = function(event) {
    			if(checkFormData()==false){
        			return _lang.confirmtoleave;
        		}
    			return ;
        	};
    	}, 1000);//这里延迟一会儿设置，不要是担心如UE等插件的数据尚未准备完毕
    }
});

/**
 * 刷新页面数据缓存
 */
function refreshFormData(){
	if(typeof getFormData!='function') dataCacheMap("getFormData", "");
	else dataCacheMap("getFormData", JSON.stringify(getFormData()));
}

/**
 * 检查页面的数据表单有无变化,无变化返回false
 */
function checkFormData(){
	if(typeof getFormData!='function') return true;
	if(dataCacheMap("getFormData")!=JSON.stringify(getFormData())) return false;
	return true;
}

/**
 * 设置或获取当前页的缓存数据
 */
var dataCache = {};
function dataCacheMap(key, value) {
    var ks = key.split('\.');
    var obj = dataCache;
    for (var i = 0; i < ks.length - 1; i++) {
        if (obj[ks[i]]) { } else {
            obj[ks[i]] = {};
        }
        obj = obj[ks[i]];
    }
    if (value) {
        obj[ks[ks.length - 1]] = value;
    }
    return obj[ks[ks.length - 1]];
}

/**
 * 从数组中查询指定属性值的对象
 */
function dataFromListMap(list, key, value, data) {
    if (list == null) return null;
    var ks = key.split('\.');
    for (var j = 0; j < list.length; j++) {
        var obj = list[j];
        for (var i = 0; i < ks.length; i++) {
            if (obj && obj[ks[i]]) { } else {
                obj = null;
                break;
            }
            obj = obj[ks[i]];
        }
        if (obj == null) continue;

        if (obj == value) {
            if (typeof data != 'undefined') {
                list[j] = data;
            }
            return list[j];
        }
    }
    if (typeof data != 'undefined') {
        list.push(data);
        return data;
    }
    return null;
}

/**
 * 切换国际化语言包
 */
function changeLang(lang){
	delCookie('org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE');
	setCookie('org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE', lang, 24*60*7);
	$.post("./responseAjax?data="+new Date().getTime()+"&lang="+lang,function(resp){
		location.reload();
	})
}

/**
 * 加载区县代码
 */
var citycodeList = {};
function citycode(pcode, obj, defaultSelect,callback){
	if(citycodeList[pcode]){
		$(obj).html(citycodeList[pcode]);
		if(defaultSelect){
			$(obj).find('option').removeAttr('selected');
			$(obj).find('option[value="'+defaultSelect+'"]').attr('selected','selected');
		}
		if(callback){
			callback.call();
		}
	}else{
		$.get("./Citycode?ajaxtag=1",{parent:pcode},function(resp){
			var s = "";
			resp.data.forEach(function(d){
				s += '<option value="'+d.qxdm+'">'+d.qxmc+'</option>';
			});
			citycodeList[pcode] = s;
			$(obj).html(citycodeList[pcode]);
			if(defaultSelect){
				$(obj).find('option').removeAttr('selected');
				$(obj).find('option[value="'+defaultSelect+'"]').attr('selected','selected');
			}
			if(callback){
				callback.call();
			}
		});
	}
}

/**
 * 设置Cookie
 */
function setCookie(name,value,minutes){
    var exp = new Date();
    exp.setTime(exp.getTime() + minutes*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

/**
 * 获取Cookie
 */
function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg)) return (arr[2]);
    
    else return null;
}

/**
 * 清除Cookie
 */
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    document.cookie= name + "=;expires="+exp.toGMTString();
}

/**
 * 遍历对象属性
 */
function whatInObj(obj){
	var s="";for(i in obj)s+=i+":"+obj[i]+"\n";alert(s);
}

/**
 * 检测ajax成功请求后返回信息
 * @param resp
 * @param object
 * @returns {Boolean}
 */
function checkResponse(resp){
	if(resp.status==0) return true;
	var message = "";
	if(resp.message){
		message = resp.message;
	}else if(_lang.responseMessages[resp.status+""]){
		message = _lang.responseMessages[resp.status+""];
	}
	if(message!=""){
		shakeMsg(message);
	}
	return false;
}
/**
 * 检测手机短信发送结果
 * @param resp
 * @returns {Boolean}
-110 同一手机号每日发送已达到5条
-120 同一IP地址每日发送已达到10条
-1	没有该用户账户
-2	接口密钥不正确 [查看密钥] 不是账户登陆密码
-21	MD5接口密钥加密不正确
-3	短信数量不足
-11	该用户被禁用
-14	短信内容出现非法字符
-4	手机号格式不正确
-41	手机号码为空
-42	短信内容为空
-51	短信签名格式不正确 接口签名格式为：【签名内容】
-6	IP限制 
>0	短信发送数量
 */

function checkSmsResult(resp){
	if(checkResponse(resp)==false) return false;
	
	if(resp.data * 1 < 0){
		shakeMsg(_lang.responseSmsMessages[""+resp.data]||_lang.responseSmsMessages['error']);
		return false;
	}else{
		return true;
	}
}

/**
 * div抖动
 * @param o
 */
function shake(o){
	var element = $(o);
	element.css('position', 'relative');
	for(var i=1; 4>=i; i++){
		element.animate({left:-(20-5*i)},50);
		element.animate({left:2*(20-5*i)},50);
    }
}

/**
 * div闪烁
 * @param o
 */
function flash(o){
	var element = $(o);
	element.addClass('backgroundRed');
	setTimeout(function () {
	    element.removeClass('backgroundRed');
	    setTimeout(function () {
	        element.addClass('backgroundRed');
	        setTimeout(function () {
	            element.removeClass('backgroundRed');
	        }, 100);
	    }, 100);
	}, 100);
}

/**
 * 显示提示消息
 * @param msg
 * @param title
 */
function showMsg(msg,title, callback){
	var t = _lang.messageTitle;
	if(title){t = title;}
	var notice = $.gritter.add({
        title: t,
        text: msg,
        image: 'images/notice.png',
        sticky: true,
        time: ''
    });
	
	if(callback){
		setTimeout(function(){
			$.gritter.remove(notice, {
	            fade: true,
	            speed: 'slow'
	        });
			callback();
		},1500);
	}else{
		setTimeout(function(){
			$.gritter.remove(notice, {
	            fade: true,
	            speed: 'slow'
	        });
		},5000);
	}
}

/**
 * 显示错误的提示消息
 */
function errorMsg(msg, title) {
    var t = _lang.messageErrorTitle;
    if (title) { t = title; }
    var notice = $.gritter.add({
        title: t,
        text: msg,
        image: 'images/notice.png',
        sticky: true,
        class_name: 'gritter-error' + ($('#gritter-light') && $('#gritter-light').get(0) && !$('#gritter-light').get(0).checked ? ' gritter-light' : ''),
        //fade_in_speed:'fast',
        time: '2000'
    });
    setTimeout(function () {
        $.gritter.remove(notice, {
            fade: true,
            speed: 'slow'
        });
    }, 5000);
}

/**
 * 抖动提示消息
 */
function shakeMsg(msg, title){
	var t = _lang.messageErrorTitle;
	if(title){t = title;}
	var notice = $.gritter.add({
        title: t,
        text: msg,
        image: 'images/notice.png',
        sticky: true,
        class_name: 'gritter-error' + ($('#gritter-light') && $('#gritter-light').get(0) && !$('#gritter-light').get(0).checked ? ' gritter-light' : ''),
        //fade_in_speed:'fast',
        time: '2000'
    });
	shake($('#gritter-notice-wrapper>div:last'));
	setTimeout(function(){
		$.gritter.remove(notice, {
            fade: true,
            speed: 'slow'
        });
	},5000);
}

/**
 * 获取当前连接中的参数
 * @param name
 * @returns
 */
function getQueryString(name, url) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	if(url){
		url = url.substr(url.indexOf('?')+1);
	}else{url = window.location.search.substr(1);}
	var r = url.match(reg);
	if (r != null) return unescape(r[2]); return null;
}

/**
 * 替换全部
 */
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);  
    } else {  
        return this.replace(reallyDo, replaceWith);  
    }  
}

/**
 * 日期格式化
 */
Date.prototype.format = function(format){ 
	var o = { 
		"M+" : this.getMonth()+1, //month 
		"d+" : this.getDate(), //day 
		"h+" : this.getHours(), //hour 
		"m+" : this.getMinutes(), //minute 
		"s+" : this.getSeconds(), //second 
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
		"S" : this.getMilliseconds() //millisecond 
	} 
	if(/(y+)/.test(format)) { 
	format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	} 
	for(var k in o) { 
		if(new RegExp("("+ k +")").test(format)) { 
		format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
		} 
	}
	if(format=='1970-01-01') return '';
	return format; 
} 

/** 
 * 将数值四舍五入(保留2位小数)后格式化成金额形式 
 * @param num 数值(Number或者String) 
 * @return 金额格式的字符串,如'1,234,567.45' 
 * @type String 
 */  
function formatCurrency(num, noDot) {
    num = num.toString().replace(/\$|\,/g,'');  
    if(isNaN(num))num = "0";  
    sign = (num == (num = Math.abs(num)));  
    num = Math.floor(num*100+0.50000000001);  
    cents = num%100;  
    num = Math.floor(num/100).toString();  
    if(cents<10)  
    cents = "0" + cents;  
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)  
    num = num.substring(0,num.length-(4*i+3))+(noDot==true?'':',')+  
    num.substring(num.length-(4*i+3));  
    return (((sign)?'':'-') + num + '.' + cents);  
} 

/**
 * 兼容 事件阻止
 * @param event
 */
function preventDefault(event){
    if(document.all){
      window.event.returnValue = false;
    }else{
      event.preventDefault();
    }
}

/**
 * 取消事件冒泡
 */
function stopBubble(e) {
    if (e && e.stopPropagation) {//非IE浏览器 
        e.stopPropagation();
    }
    else {//IE浏览器 
        window.event.cancelBubble = true;
    }
}

/**
 * 转换成UTF-8
 * @param str
 * @returns {String}
 */
function utf16to8(str) {
	var out, i, len, c;
    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
    	c = str.charCodeAt(i);
    	if ((c >= 0x0001) && (c <= 0x007F)) {
    		out += str.charAt(i); 
    	} else if (c > 0x07FF) { 
    		out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
    		out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F)); 
    		out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
    	} else {
    		out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
    		out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
    	}
    }
    return out;   
}

/**
 * "加载中"提示进度条
 * @param txt
 * @returns
 */
var progress_step = 0;
function loadingModal(txt, time){
	if($('.preloader').length>0){
		if(txt){$('.preloader').show().children('div:eq(1)').text(txt)}
		else{$('.preloader').hide().children('div:eq(1)').text('')}
		return false;
	}
	
	if($('#loadingModal').length<1){
		$('<div id="loadingModal" style="z-index:9997;display:none"><div style="position:fixed;width:100%;height:100%;left:0;top:0;z-index:9998;background:#ccc;opacity:0.5;"></div><div style="position:fixed;width:100%;height:100%;line-height:100%;top:0;z-index:9999;font-size:30px;text-align:center;"><div class="progressBar" style="border:2px solid blue;width:0"></div><span class="forText" style="color:#fff">'+_lang.loadingmsg+'</span></div></div>').appendTo('body');
	}
	var m = $('#loadingModal');
	if(m.is(':hidden')){
		m.toggle();
	}else{
		if(txt){}else{
			m.toggle();
		}
	}
	
	if(!m.is(':hidden')){
		var step = 500;
		if(time) step = time*1/4;
		var bar = m.find('.progressBar').css('width',0);
		progress_step = 1;
		bar.animate({width:'50%'},step,function(){
			progress_step = 2;
			bar.animate({width:'75%'},step,function(){
				if(progress_step<2) return false;
				progress_step = 3;
				bar.animate({width:'95%'},step,function(){
					if(progress_step<3) return false;
					progress_step = 4;
					bar.animate({width:'98%'},step*6,function(){ });
				});
			});
		});
	}
	if (txt) {
	    if (txt.indexOf('<i class="icon-spinner icon-spin"></i>') == -1) txt = '<i class="icon-spinner icon-spin"></i> ' + txt;
		m.find('.forText').html(txt);
	}
	return m;
}

/**
 * 表单进行序列化成对象
 */
$.fn.serializeObject = function(){    
   var o = {};    
   var a = this.serializeArray();
   $.each(a, function() {    
       if (o[this.name]) {    
           if (!o[this.name].push) {    
               o[this.name] = [o[this.name]];    
           }    
           o[this.name].push(this.value || '');    
       } else {    
           o[this.name] = this.value || '';    
       }    
   });    
   return o;    
};

/**
 * toggle指定标签的样式
 * @param obj
 * @param classname
 */
function toggle4class(obj, classname, single){
	if($(obj).hasClass(classname)) $(obj).removeClass(classname);
	else {
		if(single) $(obj).parent().children().removeClass(classname);
		$(obj).addClass(classname);
	}
}

/**
 * para_name 参数名称 para_value 参数值 url所要更改参数的网址
 * @param para_name
 * @param para_value
 */
function setUrlParam(para_name, para_value) {
    var strNewUrl = new String();
    var strUrl = new String();
    var url = new String();
    url= window.location.href;
    strUrl = window.location.href;
    if (strUrl.indexOf("?") != -1) {
        strUrl = strUrl.substr(strUrl.indexOf("?") + 1);
        if (strUrl.toLowerCase().indexOf(para_name.toLowerCase()) == -1) {
            strNewUrl = url + "&" + para_name + "=" + para_value;
            window.location = strNewUrl;
        } else {
            var aParam = strUrl.split("&");
            for (var i = 0; i < aParam.length; i++) {
                if (aParam[i].substr(0, aParam[i].indexOf("=")).toLowerCase() == para_name.toLowerCase()) {
                    aParam[i] = aParam[i].substr(0, aParam[i].indexOf("=")) + "=" + para_value;
                }
            }
            strNewUrl = url.substr(0, url.indexOf("?") + 1) + aParam.join("&");
            window.location = strNewUrl;
        }
    } else {
        strUrl += "?" + para_name + "=" + para_value;
        window.location=strUrl;
    }
}

/**
 * 字符串转成JSON对象
 */
if(String.prototype.toJSON){}else{
	String.prototype.toJSON = function(){
			var str = this.replace(/^s+|s+$/g, '');
			if ($.isPlainObject(str)) return str;
			var start = (str ? str.indexOf("[") : -1), options = {};
			if(start != 0) start = (str ? str.indexOf("{") : -1);
			if (start != -1) {
			    try {
			        options = (new Function("", "var json = " + str.substr(start) + "; return JSON.parse(JSON.stringify(json));"))();
			    } catch (e) {}
			}
			return options;
	};
}

/**
 * 重排表格的序号
 * @param target
 */
function resetRowIndex(target){
	$(target).children('tr:not(.norecord)').each(function(i){
		if($(this).children('td:eq(0)').find('input').length>0) $(this).children('td:eq(1)').text(i+1);
		else $(this).children('td:eq(0)').text(i+1);
	});
}

/**
 * HSV转成RGB
 * accepts parameters
 * h  Object = {h:x, s:y, v:z}
 * OR 
 * h, s, v
 */
function HSVtoRGB(h, s, v) {
    var r, g, b, i, f, p, q, t;
    if (arguments.length === 1) {
        s = h.s, v = h.v, h = h.h;
    }
    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q = v * (1 - f * s);
    t = v * (1 - (1 - f) * s);
    switch (i % 6) {
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }
    return 'rgb('+Math.round(r * 255)+','+Math.round(g * 255)+','+Math.round(b * 255)+')';
    /*return {
        r: Math.round(r * 255),
        g: Math.round(g * 255),
        b: Math.round(b * 255)
    };*/
}

/**
 * RGB转换成HSV
 * r  Object = {r:x, g:y, b:z}
 * OR 
 * r, g, b
 */
function RGBtoHSV(r, g, b) {
    if (arguments.length === 1) {
        g = r.g, b = r.b, r = r.r;
    }
    var max = Math.max(r, g, b), min = Math.min(r, g, b),
        d = max - min,
        h,
        s = (max === 0 ? 0 : d / max),
        v = max / 255;

    switch (max) {
        case min: h = 0; break;
        case r: h = (g - b) + d * (g < b ? 6: 0); h /= 6 * d; break;
        case g: h = (b - r) + d * 2; h /= 6 * d; break;
        case b: h = (r - g) + d * 4; h /= 6 * d; break;
    }

    return {
        h: h,
        s: s,
        v: v
    };
}

/**
 * HSV转成HSL
 */
function HSVtoHSL(h, s, v) {
    if (arguments.length === 1) {
        s = h.s, v = h.v, h = h.h;
    }
    var _h = h,
        _s = s * v,
        _l = (2 - s) * v;
    _s /= (_l <= 1) ? _l : 2 - _l;
    _l /= 2;

    return {
        h: _h,
        s: _s,
        l: _l
    };
}

/**
 * HSL颜色转换成HSV格式
 */
function HSLtoHSV(h, s, l) {
    if (arguments.length === 1) {
        s = h.s, l = h.l, h = h.h;
    }
    var _h = h,
        _s,
        _v;

    l *= 2;
    s *= (l <= 1) ? l : 2 - l;
    _v = (l + s) / 2;
    _s = (2 * s) / (l + s);

    return {
        h: _h,
        s: _s,
        v: _v
    };
}

/**
 * 求两圆的相交点
 */
var circleIntersectPoint_lim0=0.000000001;
function circleIntersectPoint(x1,y1,r1,x2,y2,r2){
    var d,a,b,c,p,q,r,c1,c2,s1,s2,xs1,ys1,xs2,ys2;
    d = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
    if(circleIntersectPoint_lim0>Math.abs(d-r1-r2)||circleIntersectPoint_lim0>Math.abs(d-Math.abs(r1-r2))){
        a = 2.0*r1*(x1-x2);
        b = 2.0*r1*(y1-y2);
        c = r2*r2-r1*r1-(x1-x2)*(x1-x2)-(y1-y2)*(y1-y2);
        p = a*a+b*b;
        q = -2.0*a*c;
        c1 = -q/p/2.0;
        s1 = Math.sqrt(1-c1*c1);
        xs1 = r1*c1+x1;
        ys1 = r1*s1+y1;
        if(circleIntersectPoint_lim0<Math.abs((xs1-x2)*(xs1-x2)+(ys1-y2)*(ys1-y2)-r2*r2)){
            ys1 = -r1*s1+y1;
        }
        return [xs1, ys1];
    }else{
        a = 2.0*r1*(x1-x2);
        b = 2.0*r1*(y1-y2);
        c = r2*r2-r1*r1-(x1-x2)*(x1-x2)-(y1-y2)*(y1-y2);
        p = a*a+b*b;
        q = -2.0*a*c;
        r = c*c-b*b;
        c1 = (Math.sqrt(q*q-4.0*p*r)-q)/p/2.0;
        c2 = (-Math.sqrt(q*q-4.0*p*r)-q)/p/2.0;
        s1 = Math.sqrt(1-c1*c1);
        s2 = Math.sqrt(1-c2*c2);
        xs1 = r1*c1+x1;
        xs2 = r1*c2+x1;
        ys1 = r1*s1+y1;
        ys2 = r1*s2+y1;

        if(circleIntersectPoint_lim0<Math.abs((xs1-x2)*(xs1-x2)+(ys1-y2)*(ys1-y2)-r2*r2)){
            ys1=-r1*s1+y1;
        }
        if(circleIntersectPoint_lim0<Math.abs((xs2-x2)*(xs2-x2)+(ys2-y2)*(ys2-y2)-r2*r2)){
            ys2=-r1*s2+y1;
        }
        if(circleIntersectPoint_lim0>Math.abs(ys1-ys2)&&circleIntersectPoint_lim0>Math.abs(xs1-xs2)){
            if(ys1>y1){
                ys2=2.0*y1-ys1;
            }else{
                ys1=2.0*y1-ys1;
            }
        }

        var result = [0, 0];

        /****有向线段 的右侧****/
        if(x1<x2) result[1] = Math.max(ys1, ys2);
        else result[1] = Math.min(ys1, ys2);

        if(y1<y2) result[0] = Math.min(xs1, xs2);
        else result[0] = Math.max(xs1, xs2);
        /********/

        return result;
    }
}


/*=============公共的操作===========*/

/**
 * 添加/删除 收藏/点赞/想去
 * @param sid
 * @param type
 * @param flag
 * @param isRemove
 * @param target
 */
function collect(sid, type, flag, isRemove, target){
	$.post("collect?ajaxtag=1",{sid:sid, type:type, flag:flag, isRemove:isRemove},function(resp){
		if(checkResponse(resp)==false) return ;
		
		if(flag==1){
			showMsg(isRemove?_lang.messageSuccessDeleteCollect:_lang.messageSuccessAddCollect);
		}else if(flag==2){
			showMsg(isRemove?_lang.messageSuccessDeleteLikeit:_lang.messageSuccessAddLikeit);
		}else if(flag==3){
			showMsg(isRemove?_lang.messageSuccessDeleteWantgo:_lang.messageSuccessAddWantgo);
		}
		
		if(target){
			if('function' == typeof target){
				target();
			}else{
				if(isRemove){
					$(target).parent().find('.heart').removeClass('hasCollect');
				}else{
					$(target).parent().find('.heart').addClass('hasCollect');
				}
				
				$(target).text($(target).text()?($(target).text()*1+resp.data):resp.data);
			}
		}
	});
}

/**
 * 举报
 */
function report(sid,type){
	var dialog = bootbox.dialog({
		title: _lang.reportDialogTitle,
		message: '<div class="row"><div class="col-xs-12"><textarea rows="5" class="reason col-xs-12 form-control" style="padding:10px 15px;" placeholder="'+_lang.reportDialogTitlePlaceholder+'"></textarea></div></div>',
		buttons:[{
			label: '<i class="icon icon-ok"></i> '+_lang.buttonSubmit,
			className:'',
			callback: function(){
				var reason = dialog.find(".reason").val().trim();
				if(reason.length<1||reason.length>4000){
					errorMsg(_lang.reportDialogEmptyError);
					flash(dialog.find(".reason"));
					return false;
				}

				$.post("report?ajaxtag=1",{sid:sid,type:type,reason:reason},function(resp){
					if(checkResponse(resp)==false) return false;
					showMsg(_lang.reportDialogHasSendSuccess)
				});
			}}]
	});
}

/**
 * 删除指定id的对象
 */
function deleteEntity(id, url, cb) {
    bootbox.confirm("<h4>"+_lang.messageConfirmTitle+"</h4>"+_lang.confirmToDelete, function (isOK) {
        if (isOK) {
            $.post(url, { id: id }, function (resp) {
                if (checkResponse(resp) == false) return false;

                showMsg(_lang.messageSuccessDelete);
                if (cb) cb(resp);
            });
        }
    });
}

/*

                               ____                  
                            _.' :  `._               
                        .-.'`.  ;   .'`.-.           
               __      / : ___\ ;  /___ ; \      __  
             ,'_ ""=-.:__;".-.";: :".-.":__;.-="" _`,
             :' `.t""=-.. '<@.`;_  ',@:` ..-=""j.' `;
                  `:-.._J '-.-'L__ `-.-' L_..-;'     
                    "-.__ ;  .-"  "-.  : __.-"       
                        L ' /.======.\ ' J           
                         "-.   "__"   .-"            
                        __.l"-:_JL_;-";.__           
                     .-j/'.;  ;""""  / .'\"-.        
                   .' /:`. "-.:     .-" .';  `.      
                .-"  / ;  "-. "-..-" .-"  :    "-.   
             .+"-.  : :      "-.__.-"      ;-._   \  
             ; \  `.; ;                    : : "+. ; 
             :  ;   ; ;                    : ;  : \: 
             ;  :   ; :                    ;:   ;  : 
            : \  ;  :  ;                  : ;  /  :: 
            ;  ; :   ; :                  ;   :   ;: 
            :  :  ;  :  ;                : :  ;  : ; 
            ;\    :   ; :                ; ;     ; ; 
            : `."-;   :  ;              :  ;    /  ; 
             ;    -:   ; :              ;  : .-"   : 
             :\     \  :  ;            : \.-"      : 
              ;`.    \  ; :            ;.'_..-=  / ; 
              :  "-.  "-:  ;          :/."      .'  :
               \         \ :          ;/  __        :
                \       .-`.\        /t-""  ":-+.   :
                 `.  .-"    `l    __/ /`. :  ; ; \  ;
                   \   .-" .-"-.-"  .' .'j \  /   ;/ 
                    \ / .-"   /.     .'.' ;_:'    ;  
                     :-""-.`./-.'     /    `.___.'   
                           \ `t  ._  /               
                            "-.t-._:'                
*/